package tech.wetech.admin.web.controller.system;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.applet.Main;
import tech.wetech.admin.annotation.SystemLog;
import tech.wetech.admin.common.base.Page;
import tech.wetech.admin.common.base.PageResultSet;
import tech.wetech.admin.common.base.Result;
import tech.wetech.admin.model.system.Photo;
import tech.wetech.admin.model.system.Role;
import tech.wetech.admin.service.system.FileStorageService;
import tech.wetech.admin.service.system.OrganizationService;
import tech.wetech.admin.service.system.PhotoService;
import tech.wetech.admin.service.system.RoleService;
import tech.wetech.admin.web.controller.base.BaseController;
import tech.wetech.admin.web.dto.system.RoleDto;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.UUID;

@Controller
@RequestMapping("/photo")
public class PhotoController extends BaseController {
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Value("${file.thumbnail-dir}")
    private String thumbUploadDir;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private FileStorageService fileStorageService;

    private static final Logger log = LoggerFactory.getLogger(Main.class);
    @RequestMapping(method = RequestMethod.GET)
    @RequiresPermissions("photo:view")
    public String toPage(Model model) {
        setCommonData(model);
        return "system/photo";
    }

    @ResponseBody
    @RequestMapping("/list")
    @RequiresPermissions("photo:view")
    public PageResultSet<Photo> list(Page page) {
        return photoService.findByPage(page);
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(
            @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
         // 获取上传目录的绝对路径（相对于 Web 应用根目录）
        String uploadPath = request.getServletContext().getRealPath("/uploads/");
        System.out.println("Upload Path: " + uploadPath);
        String originalName = file.getOriginalFilename();
        String filename = UUID.randomUUID() + "_" + originalName;
        String thumbnailPath = request.getServletContext().getRealPath("/uploads/thumbnails/");
        Path targetPath = Paths.get(uploadPath, filename);
        Timestamp uploadTime = new Timestamp(System.currentTimeMillis());
        String thumbName = "thumb_" + filename;
        // 存储相对路径到数据库
        String relativeUploadPath = uploadDir + filename; // 相对路径
        String relativeThumbnailPath = thumbUploadDir + thumbName; // 相对路径

        // 确保目录存在
        File outputFile = new File(thumbnailPath + File.separator + thumbName);
        File parentDir = outputFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();

            // 复制文件到目标路径
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);

            // 重置输入流（如果支持 mark/reset）
            if (inputStream.markSupported()) {
                inputStream.reset();
            } else {
                // 如果不支持 mark/reset，重新获取输入流
                inputStream.close();
                inputStream = file.getInputStream();
            }

            // 生成缩略图
            try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                BufferedImage thumbnail = Thumbnails.of(inputStream)
                        .size(200, 200)
                        .asBufferedImage();
                ImageIO.write(thumbnail, "jpg", fos);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Photo photo = new Photo(originalName, relativeUploadPath, relativeThumbnailPath,uploadTime);
        // 保存到数据库
        photoService.createPhoto(photo);

        return ResponseEntity.ok("上传成功");
    }

    @ResponseBody
    @RequiresPermissions("photo:update")
    @SystemLog("角色管理更新角色")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@Valid Photo photo) {
        photoService.updatePhoto(photo);
        return Result.Success();
    }

    @ResponseBody
    @RequiresPermissions("photo:delete")
    @SystemLog("角色管理删除角色")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @Transactional
    public Result delete(@RequestParam("id") Long id) {
        Photo photo = photoService.findById(id);
        if (photo == null) {
            throw new RuntimeException("Photo not found with id: " + id);
        }

        String storagePath = photo.getStoragePath();
        String thumbnailPath = photo.getThumbnailPath();

        try {
            if (storagePath != null && !storagePath.isEmpty()) {
                fileStorageService.deleteFile(storagePath);
            }
        } catch (Exception e) {
            log.error("Failed to delete storage file: " + storagePath, e);
            throw new RuntimeException("Failed to delete storage file", e);
        }

        try {
            if (thumbnailPath != null && !thumbnailPath.isEmpty()) {
                fileStorageService.deleteFile(thumbnailPath);
            }
        } catch (Exception e) {
            log.error("Failed to delete thumbnail file: " + thumbnailPath, e);
            throw new RuntimeException("Failed to delete thumbnail file", e);
        }

        photoService.deletePhoto(id);
        return Result.Success();
    }

    private void setCommonData(Model model) {
        model.addAttribute("organizationList", organizationService.findAll());
        model.addAttribute("roleList", roleService.findAll());
    }
}
